export default class {
  constructor(options) {
    this.options = options
    this.connected = false
    this.reconnectInterval = 5000 // 重连间隔时间
    this.reconnectTimeoutID = null // 重连定时器 ID

    this.connect()
  }

  connect() {
    this.ws = new WebSocket(this.options.url)

    // 连接成功
    this.ws.onopen = () => {
      console.log('[WS] 连接成功')
      this.connected = true

      setInterval(() => {
        this.send({ type: 'ping' })
      }, 30 * 1000)
    }

    // 连接关闭
    this.ws.onclose = e => {
      console.log('[WS] 连接关闭', e)
      this.connected = false
      this.reconnect()
    }

    // 连接失败
    this.ws.onerror = error => {
      console.error('[WS] 连接失败', error)
    }

    // 收到消息
    this.ws.onmessage = e => {
      const data = JSON.parse(e.data)

      console.log('[WS] 收到消息', data)
      
      this.options?.onMessage && this.options?.onMessage(data)
    }
  }

  send(data) {
    this.ws.send(JSON.stringify(data))
  }

  // 重连
  reconnect() {
    if (this.reconnectTimeoutID) clearTimeout(this.reconnectTimeoutID)

    this.reconnectTimeoutID = setTimeout(() => {
      console.log('[WS] 重连中')
      this.connect()
    }, this.reconnectInterval)
  }

  // 销毁
  close() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }

    if (this.reconnectTimeoutID) {
      clearTimeout(this.reconnectTimeoutID)
      this.reconnectTimeoutID = null
    }
  }
}
